package com.service.scheduling.task;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.service.dao.model.SysQuotesChia;
import com.service.scheduling.service.SysQuotesChiaService;
import com.service.scheduling.utils.MemCacheNoTran;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Slf4j
@Component
public class ChiaInfoTask {

	@Autowired
	private MemCacheNoTran memCache;

	@Autowired
	private SysQuotesChiaService sysQuotesChiaService;

	private String url;


	/**
	 * 每分钟执行一次更新到缓存
	 */
//	@Scheduled(cron = "0 0 */1 * * ?")
	public void chiaInfoTask() {
		try{
			SysQuotesChia sysQuotesChia = null;//getChiaSummary();
			LambdaQueryWrapper<SysQuotesChia> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.orderByDesc(SysQuotesChia::getId);
			queryWrapper.last("limit 1");
			SysQuotesChia quotesChia = sysQuotesChiaService.getOne(queryWrapper);
			if(!ObjectUtils.isEmpty(sysQuotesChia)){
				if(!ObjectUtils.isEmpty(quotesChia)){
					sysQuotesChia.setId(quotesChia.getId());
				}
				String json = JSONObject.toJSON(sysQuotesChia).toString();
				//添加/更新到redis缓存
				String CHIA_CONFIG_KEY = "chia_config";
				memCache.setNoExpire(CHIA_CONFIG_KEY,json);
				sysQuotesChiaService.saveOrUpdate(sysQuotesChia);
			}else{
				log.error("Update failed! Cannot request chia summary data");
			}
		}catch (Exception e){
			log.error(e.getMessage());
		}
	}

	/**
	 * 查询chia
	 * @return
	 */
//	private SysQuotesChia getChiaSummary(){
//		HttpResponse response = HttpRequest.get(url+"/blockchainSummary").execute();
//		log.info("getBlockchainSummary result:<status:{},body:{}>", response.getStatus(), response.body());
//		String result = response.body();
//		return org.apache.commons.lang3.StringUtils.isNotBlank(result) ? JSONObject.parseObject(result, SysQuotesChia.class) : null;
//	}
}
